package mycompany.service;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.*;
import mycompany.model.UserBaseModel;

/**
 * 
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 */
public class UserService {
    
    private static final UserService INSTANCE = new UserService();
    private static final Logger log = Logger.getLogger(UserService.class.toString());
    private static List<UserBaseModel> users;
    
    /**
     * Constructs an instance
     */
    private UserService(){
        users = new ArrayList<UserBaseModel>();
    }
    
    /**
     * Returns a singleton instance
     * @return 
     */
    public static UserService getInstance(){
        return INSTANCE;
    }
    
    public UserBaseModel indentifyUser(HttpSession session){
        UserBaseModel user = getUserBySessionId(session.getId());
        if(user==null) user = addUser(session);
        return user;
    }
    
    public UserBaseModel addUser(HttpSession session){
        UserBaseModel user = new UserBaseModel(session);
        log.log(Level.INFO, "{0} was added to user list", user.getName());
        users.add(user);
        return user;
    }
    
    public void removeUser(HttpSession session){
        UserBaseModel user = getUserBySessionId(session.getId());
        if(user!=null){
            log.log(Level.INFO, "{0} was removed from user list", user.getName());
            users.remove(user);
        }
    }
    
    public List<UserBaseModel> getUsers(){
        return users;
    }
    
    public UserBaseModel getUserBySessionId(String sessionId){
        UserBaseModel result = null;
        for(UserBaseModel user : users){
            if(user.isUserSessionIdEquals(sessionId)) result = user;
        }
        return result;
    }

    public int getUsersCount(){
        log.log(Level.INFO, "{0}", users.size());
        return users.size();
    }
}
